﻿using AForge.Video;
using Scrat.Core.Pojo;
using Sunny.UI;
using System;
using System.IO;
using System.Net;
using System.Windows;

namespace Scrat.Teacher.Pages
{
    public partial class StuDemonstrationPage : UIPage
    {
        private MainForm _parent;

        private IPAddress _stuServerIPAddr; 
        private int _stuScreenShringPort;

        public StuDemonstrationPage(MainForm parent)
        {
            InitializeComponent();
            _parent = parent;
        }

        private void StuDemonstrationPage_Shown(object sender, System.EventArgs e)
        {
            _parent.RequireStuDemonstrateEvent += OnStartStuDemonstrate;
            _parent.StopStuDemonEvent += OnStopStuDemonstrate;
        }

        private void OnStopStuDemonstrate()
        {
            try
            {
                videoSourcePlayer?.Stop();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace.ToString());
            }
            
        }

        private void OnStartStuDemonstrate(Datagram datagram)
        {
            Invoke(new Action(() => { ConnectStuDemon(datagram); }));
        }

        public void ConnectStuDemon(Datagram datagram)
        {
            _stuServerIPAddr = datagram.RemoteIPAddr;
            _stuScreenShringPort = datagram.RemotePort;

            // 尝试连接
            if (!videoSourcePlayer.IsRunning)
            {
                string url = string.Concat("http://", _stuServerIPAddr.ToString(), ":", _stuScreenShringPort);
                // ShowErrorDialog(url);
                try
                {
                    MJPEGStream stream = new MJPEGStream(url);
                    videoSourcePlayer.VideoSource = stream;
                    videoSourcePlayer.Start();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace.ToString());
                }
                finally
                {
                    // 如果没有运行 那么我们再次尝试连接,直到连接上为止
                    if (!videoSourcePlayer.IsRunning)
                    {
                        ConnectStuDemon(datagram);
                    }
                }

            }
        }
    }
}
